// server.js
let WebSocket = require("ws");
let wss = new WebSocket.Server({
    port: 3000
});
let clients = new Set(); // 已连接的客户端

wss.on('connection', (ws) => {
    console.log('WebSocket连接已建立');
    ws.readyState === WebSocket.OPEN && clients.add(ws)
    ws.on('message', (message) => {
        // 发送消息给客户端
        clients.forEach((client) => {
            if (client.readyState === WebSocket.OPEN) {
                client.send(message);
            }
        });
    });

    ws.on('close', () => {
        console.log('WebSocket连接已关闭');
        clients.delete(ws);
    });
});